<template>
  <view class="videoDetail_container app_container_page">
    <view class="top">
      <video
        :title="topMsg.title ? topMsg.title : ''"
        id="myVideo"
        :src="isEnhanced === '1' ? (isPayOK ? topMsg.lUrl : topMsg.sUrl) : topMsg.lUrl"
        @loadedmetadata="getMetaDataFn"
        @ended="videoEndFn"
        :show-center-play-btn="!isShowControl"
        :controls="!isShowControl"
      >
        <cover-view v-if="isShowControl" class="coverView">免费观看{{ coverMinutes > 0 ? coverMinutes + '分钟' : second + '秒' }}，购买可解锁完整视频 </cover-view>
        <cover-view v-if="isShowControl" class="videoLang">{{ time }}</cover-view>
      </video>
      <view class="content">
        <view class="title">
          {{ topMsg.title ? topMsg.title : '--' }}
        </view>
        <view class="time">
          {{
            topMsg.updateTime
              ? dayjs(new Date()).format('YYYY-MM-DD') === dayjs(topMsg.updateTime).format('YYYY-MM-DD')
                ? dayjs(topMsg.updateTime).from(dayjs())
                : topMsg.updateTime
              : topMsg.createTime
              ? dayjs(new Date()).format('YYYY-MM-DD') === dayjs(topMsg.createTime).format('YYYY-MM-DD')
                ? dayjs(topMsg.createTime).from(dayjs())
                : topMsg.createTime
              : ''
          }}
        </view>
        <view class="bottom">
          <view class="bottomLeft">
            <view v-show="iscollection == 1">
              <view class="collection" @click="toCancelCollect">
                <view class="cancelCollection-icon" mode=""></view>
                取消收藏
              </view>
            </view>
            <view v-show="iscollection == 0">
              <view class="collection" @click="toCollection">
                <view class="collection-icon" mode=""></view>
                收藏
              </view>
            </view>
            <button class="share" :plain="true" data-name="shareBtn" open-type="share">
              <view class="share-icon"></view>
              <view>分享</view>
            </button>
          </view>
          <van-button type="default" class="buyBtn" v-if="isEnhanced === '1' ? (isPayOK ? false : true) : false" @click="toBuyVideo">
            ￥{{ topMsg.price ? topMsg.price : '--' }}解锁完整视频
          </van-button>
        </view>
      </view>
    </view>
    <view class="videoDetailList" v-if="isEnhanced === '0'">
      <view class="Title">推荐视频 </view>
      <pullRefreshView class="pullRefreshVideoView" ref="pullVideoView" :fetchFn="fetchVideoList">
        <template v-slot:default="{ list }">
          <appVideoListCard v-for="video in list" :key="video.id" :video="video" @VIDEOLIST_CARD_CLICK="toVideoDetail" />
        </template>
      </pullRefreshView>
    </view>
    <view class="enhanceContent" v-else>
      <view class="yql-snow">
        <rich-text class="ql-editor content" :nodes="graphicDetails"> </rich-text>
      </view>
    </view>
  </view>
</template>

<script>
import dayjs from 'dayjs'
import pullRefreshView from '@/components/app/pull-refresh-view.vue'
import appVideoListCard from '@/components/app/app_videoList_card.vue'
import { getRelatedVideoList, findVideoById, collectProduct, cancelCollect, isCollect } from '@/api/home'
import { onLaunchPromise } from '@/util/helper'
export default {
  components: {
    appVideoListCard,
    pullRefreshView
  },
  data() {
    return {
      dayjs: null,
      iscollection: 0,
      topMsg: {},
      id: '',
      isEnhanced: '',
      graphicDetails: '',
      videoContext: null,
      isShowControl: this.isEnhanced === '1' ? !this.isPayOK : false, // 是否显示30s
      // 是否付费payFlag
      isPayOK: false, // 支付成功
      time: '',
      minutes: '',
      second: '',
      coverMinutes: '' // 覆盖在上面的时长
    }
  },
  methods: {
    fmtData(val) {
      return dayjs(val).from(dayjs())
    },
    getMetaDataFn(e) {
      const duration = e.detail.duration
      this.minutes = parseInt(duration / 60) < 10 ? '0' + parseInt(duration / 60) : parseInt(duration / 60)
      this.coverMinutes = parseInt(duration / 60)
      this.second = Math.floor(duration % 60) < 10 ? '0' + Math.floor(duration % 60) : Math.floor(duration % 60)
      this.time = this.minutes + ':' + this.second
    },
    videoEndFn() {
      this.videoContext.exitFullScreen()
      this.isShowControl = this.isEnhanced === '1' ? !this.isPayOK : false
    },
    // 富文本部分反解析
    UnchangeContent(str) {
      return str ? str.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/quot;/g, '"').replace(/<img/g, '<img style="max-width: 100%;"') : ''
    },
    // TODO:
    async toBuyVideo() {
      try {
        const res = await this.$uniPromisify.appPayment({
          nonce_str: this.topMsg.price,
          productId: this.id,
          productType: 1,
          productName: `视频: ${this.topMsg.title}`,
          productNum: 1,
          totalPrice: this.topMsg.price
        })
        console.log('ssss', res)
        if (res && res.errMsg === 'requestPayment:ok') {
          this.isPayOK = true
          this.isShowControl = false
        } else {
          uni.showToast({
            icon: 'none',
            title: res.errMsg
          })
        }
      } catch (error) {
        console.log('pay error', error)
      }
    },
    fetchVideoList(params) {
      return getRelatedVideoList({
        ...params,
        videoId: this.$parent.id
      })
    },
    // 判断收藏状态
    CollectionState() {
      isCollect({
        productId: this.topMsg.id,
        productType: 1
      })
        .then((res) => {
          if (res.code === 200) {
            this.iscollection = res.data.isCollect
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    toCollection() {
      collectProduct({
        productId: this.topMsg.id,
        productType: 1
      })
        .then((res) => {
          if (res.code === 200) {
            this.iscollection = 1
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    toCancelCollect() {
      cancelCollect({
        productId: this.topMsg.id,
        productType: 1
      })
        .then((res) => {
          if (res.code === 200) {
            this.iscollection = 0
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    toVideoDetail(val) {
      uni.navigateTo({
        url: '/pages/videoDetail/index?id=' + val.id
      })
    }
  },
  created() {
    this.dayjs = dayjs
  },
  async onLoad(val) {
    this.id = val.id

    await onLaunchPromise

    findVideoById({
      videoId: val.id
    }).then((res) => {
      this.topMsg = res.data
      this.isEnhanced = res.data.isEnhanced
      this.isPayOK = res.data.payFlag
      this.graphicDetails = res.data.graphicDetails ? this.UnchangeContent(res.data.graphicDetails) : ''
      console.log(this.graphicDetails)
      this.CollectionState()
    })
  },
  onShareAppMessage(res) {
    return {
      path: '/pages/videoDetail/index?id=' + this.id
    }
  },
  onReady(res) {
    this.videoContext = uni.createVideoContext('myVideo')
  },
  onPullDownRefresh() {
    if (this.isEnhanced === '0') {
      this.$refs.pullVideoView.fetchList(true).then(() => {
        uni.stopPullDownRefresh()
      })
    }
  },
  onReachBottom() {
    if (this.isEnhanced === '0') {
      this.$refs.pullVideoView.fetchList()
    }
  }
}
</script>

<style lang="scss">
.videoDetail_container {
  .Title {
    width: 100%;
    height: 99rpx;
    line-height: 99rpx;
    font-size: 40rpx;
  }

  .top {
    #myVideo {
      width: 100%;
      height: 360rpx;
      color: #ffffff;
      .coverView {
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.4);
        font-size: 30rpx;
        line-height: 360rpx;
        text-align: center;
      }
      .videoLang {
        width: 90rpx;
        height: 30rpx;
        background-color: rgba(0, 0, 0, 0.4);
        border-radius: 15rpx;
        position: absolute;
        bottom: 21rpx;
        font-size: 24rpx;
        right: 30rpx;
        text-align: center;
        line-height: 30rpx;
      }
    }

    .content {
      width: 100%;
      min-height: 210rpx;
      background: #ffffff;
      box-shadow: 0px 20rpx 60rpx 0px rgba(0, 0, 0, 0.1);
      padding: 12rpx 30rpx;

      .title {
        font-size: 40rpx;
        line-height: 52rpx;
      }

      .time {
        height: 58rpx;
        line-height: 58rpx;
        font-size: 24rpx;
        color: #999999;
        margin-bottom: 23rpx;
      }

      .bottom {
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .bottomLeft {
          display: flex;
          align-items: center;
          .collection {
            display: flex;
            align-items: center;
          }
          .share {
            margin-left: 32rpx;
            display: flex;
            align-items: center;
            padding: 0;
            font-size: 30rpx;
            border: none;
          }
        }
        .buyBtn {
          button {
            min-width: 260rpx;
            height: 60rpx;
            background: #ffbf29;
            border-radius: 30rpx;
            padding: 0;
            height: 60rpx;
            font-size: 24rpx;
            color: #ffffff;
            padding: 0 30rpx;
          }
        }
      }
    }
  }
  .videoDetailList {
    padding: 0 30rpx;
    app-video-list-card ~ app-video-list-card {
      margin-top: 30rpx;
    }
  }
  .enhanceContent {
    padding: 30rpx;
  }
}
</style>
